package com.adingxiong.cft.service.impl;

import com.adingxiong.cft.common.service.RedisService;
import com.adingxiong.cft.entity.Role;
import com.adingxiong.cft.entity.TUser;
import com.adingxiong.cft.service.IRoleService;
import com.adingxiong.cft.service.ITUserService;
import com.adingxiong.cft.service.UserCacheService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName UserCacheServiceImpl
 * @Description TODO
 * @Author xiongchao
 * @Date 2020/10/14 11:18
 **/
@Service
public class UserCacheServiceImpl implements UserCacheService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private ITUserService userService;

    @Autowired
    private IRoleService roleService;


    private static final String CACHE_KEY = "user";

    private static final long EXPORE = 24*60*60;



    @Override
    public void delUser(Integer id) {
        TUser user = userService.getById(id);
        if(user != null) {
            String  key =   CACHE_KEY + ":" + user.getUsername();
            redisService.del(key);
        }
    }

    @Override
    public void delRole(Integer id) {
        List<Role> list = roleService.getUserRole(id);
        if(CollectionUtils.isNotEmpty(list)){
            String key = "role:list";
            redisService.lRemove(key,list.size(),list);
        }
    }

    @Override
    public void setUserInfo(TUser userInfo) {
        String key = CACHE_KEY + ":" + userInfo.getUsername();
        redisService.set(key,userInfo,EXPORE);
    }

    @Override
    public void setUserList(List<TUser> list) {
        String key = CACHE_KEY + ":list";
        redisService.lPush(key,list,EXPORE);
    }

    @Override
    public void setUserRoles(List<Role> list) {
        String key = "role:list";
        redisService.lPush(key,list,EXPORE);
    }

    @Override
    public TUser getUser(String username) {
        String key = CACHE_KEY + ":" + username;
        return (TUser) redisService.get(key);
    }

    @Override
    public List<Role> getRoles(Integer id) {
        return null;
    }
}
